import Vue from 'vue'
import Vuex from 'vuex'
import Server from '../utils/Server'
import fsPromises from 'fs/promises';
Vue.use(Vuex)
export default new Vuex.Store({
    state: {
        /** 服务器列表 */
        servers : [],
        /** 当前服务器索引 */
        serverCurIndex : null,
    },
    getters : {
        /** */
        servers( state ) {
            return state.servers;
        },
        /** */
        serverCurrent( state ) {
            return state.servers[state.serverCurIndex];
        },
        /** */
        serverCurIndex( state ) {
            return state.serverCurIndex;
        }
    },
    mutations: {
        /** */
        serversSet( state, servers ) {
            state.servers = servers;
        },
        /** */
        serverCurIndexSet( state, index ) {
            state.serverCurIndex = index;
        },
        /** */
        serverAppend( state, server ) {
            let instance = new Server(server);
            state.servers.push(instance);
        }
    },
    actions: {
        /** */
        async init(context) {
            let servers = [];
            let files = await fsPromises.readdir('./data');
            for ( let i=0; i<files.length; i++ ) {
                let path = `./data/${files[i]}/server.json`;
                let content = await fsPromises.readFile(path,{encoding:'utf8'});
                content = JSON.parse(content);
                let instance = new Server(files[i], content);
                servers.push(instance);
            }
            context.commit('serversSet', servers);
        },

        /** */
        async serverSwitch( context, id ) {
            context.commit('serverCurIndexSet',id);
        },

        async serverCurClosed( context, id ) {
            context.commit('serverCurIndexSet', null);
        }
    },
    modules: {
    }
})
